
import json
from sqlalchemy import asc,desc,or_,and_,Column,text
from flask import Blueprint, request, render_template
from sqlalchemy import desc
from applications.common.utils.http import  table_api, success_api, fail_api
from applications.schemas import YeOperationDetectionSchema
from applications.common.utils.transactional import transactional
from applications.common.utils.validate import str_escape
from applications.models import YeOperationDetection,YeOperationSetting,YeManyRelationship
from applications.extensions import db
from applications.common import curd
from applications.common.utils.sqlUtil import SqlUtil

'''
检测标志接口
'''
operationDetectionView = Blueprint('operationDetectionView', __name__, url_prefix='/ye/operationDetection')



## 分组相关接口
# 增加修改
@operationDetectionView.post('/saveOrUpdate')
@transactional(rollback = True)
def saveOrUpdate():
    # req_json = request.get_json(force=True)
    requestData = request.get_data()
    req_json = json.loads(requestData)
    for item in req_json :
        tempData =  dict(
            id = item.get("id"),
            alias = str_escape(item.get("alias")),
            remarks = str_escape(item.get("remarks")),
            picture_url = str_escape(item.get("picture_url")),
            priority_level = item.get("priority_level"),
            feature_point = item.get("feature_point"),
            group_id =  item.get("group_id"),
            group_sort =  item.get("group_sort"),
        )
        if tempData.get("id") is None : 
            # 增加
            d = YeOperationDetection(tempData)
            db.session.add(d)
            if(tempData.get("group_id") is not None) : 
                d2 = YeManyRelationship(mian_id=tempData.get("group_id"),
                                        second_id=d.id,
                                        sort=tempData.get("group_sort"), 
                                        type='second-group:operation-detection'
                                        )
                db.session.add(d2)
        elif tempData.get("id") is not None and tempData.get("group_id") is not None:
            # 删除关联关系
            YeManyRelationship.query.filter(
                YeManyRelationship.mian_id == tempData.get("group_id"), 
                YeManyRelationship.type == 'second-group:operation-detection', 
            ).delete()
            # 增加关联关系
            d2 = YeManyRelationship(mian_id=tempData.get("group_id"),
                                        second_id=tempData.get("id"),
                                        sort=tempData.get("group_sort"), 
                                        type='second-group:operation-detection'
                                        )
            db.session.add(d2)
        else:
            # 修改
            d = YeOperationDetection.query.filter_by(id=id)
            # 删除关联关系
            YeManyRelationship.query.filter(
                YeManyRelationship.id == tempData.get("group_id"), 
                YeManyRelationship.type == 'second-group:operation-detection', 
            ).delete()
            # 增加关联关系
            d2 = YeManyRelationship(mian_id=tempData.get("group_id"),
                                        second_id=tempData.get("id"),
                                        sort=tempData.get("group_sort"), 
                                        type='second-group:operation-detection'
                                        )
            d.update(tempData)
    return success_api(msg="增加或修改成功")


# 查询，通过组类型、关键字、组id 
@operationDetectionView.get('/query')
def query():
    # 获取请求参数
    keyword = request.args.get('keyword', type=str) # 关键字

    queryList = list()
    if keyword is not None and len(keyword) > 0 : queryList.append(YeOperationDetection.name.like('%{name}%'.format(name=keyword)))
    dict_all = YeOperationDetection.query.filter(and_(*queryList)).order_by(asc(YeOperationDetection.sort)).extjs_paginate()
    count = dict_all.total
    data = curd.model_to_dicts(schema=YeOperationDetection, data=dict_all.items)
    return table_api(data=data,count=count)



# 查询，通过关键字、组id 查询关联到组id上的 标志;
@operationDetectionView.get('/queryChildGroup')
def query():
    # 获取请求参数
    group_id = request.args.get('groupType', type=int) # 组类型
    keyword = request.args.get('keyword', type=str) # 关键字    
    # orm查询
    # 使用分页获取data需要.items
    baseSql = '''
        select t.id , group2.name , t.sort,t.second_id,t.mian_id,group2.type
        from ye_many_relationship t
        left join ye_operation_detection opde on opde.id = t.second_id
        ###<%=where,and%>
            ***<%=group_id%> 
                and t.mian_id = :group_id and t.type = 'second-group:operation-detection'
            ***
            ***<%=keyword%> 
                and opde.alias like '%'|| :keyword ||'%' 
            ***
        ###
        order by t.sort asc
    '''
    pageDict = SqlUtil().dynamicHandleSqlRunPage(baseSql,dict(group_id=group_id,keyword=keyword))
    data = curd.model_to_dicts(schema=YeOperationDetectionSchema, data=pageDict.data)
    return table_api(data=data, count=pageDict.count)






# 删除，并删除操作
@operationDetectionView.get('/delete')
@transactional(rollback = True)
def delete():
    # 获取请求参数
    idsStr = request.args.get('ids', type=str)
    idList = map(lambda item : int(item), idsStr.split(','))
    YeOperationDetection.query.filter(YeOperationDetection.id.in_(idList)).delete()
    YeOperationSetting.query.filter(YeOperationSetting.detection_id.in_(idList)).delete()

    type = request.args.get('type', type=str) #  删除标志, all - 删除组以及关联关系; one - 删除组一条数据;
    idList = list(map(lambda item : int(item), idsStr.split(',')))
    if type is not None and type == 'all' : 
        # 默认删除关联关系和自身
        YeManyRelationship.query.filter(
            YeManyRelationship.mian_id.in_(idList), 
            YeManyRelationship.type == 'second-group:operation-detection', 
        ).delete()
        YeOperationDetection.query.filter(YeOperationDetection.id.in_(idList)).delete()
    elif type is not None and type == 'one' :
        # 仅删除自身
        YeOperationDetection.query.filter(YeOperationDetection.id.in_(idsStr)).delete()
    elif type is not None and type == 'ship' :
        # 删除关联关系
        YeManyRelationship.query.filter(
            YeManyRelationship.id.in_(idList), 
            YeManyRelationship.type == 'second-group:operation-detection', 
        ).delete()
    return success_api(msg="删除成功")


